package com.dyx.xml.sax;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @className: SAXDemoHandel
 * @description: TODO 类描述
 * @author: dengyouxu
 * @date: 2020/4/1 1046
 **/
public class SAXDemoHandler extends DefaultHandler {



    //遍历xml文件开始标签
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        System.out.println("sax解析开始=====startDocument=====");
    }

    //遍历xml文件结束标签
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println("sax解析结束=====endDocument=====");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        System.out.println("====startElement(uri==>" + uri + ",localName==>" + localName + ",qName==>" + qName +
                ",attributes==>" + parseAttributes(attributes) + ")");
    }

    public String parseAttributes(Attributes attributes) {
        if (attributes == null || attributes.getLength() == 0) {
            return "";
        }
        int length = attributes.getLength();
        StringBuilder attributeContent = new StringBuilder("\n");
        for (int i = 0; i < length; i++) {
            String uri = attributes.getURI(i);
            attributeContent.append(" the uri of index i=[").append(i).append("] is ").append(uri).append("\n");
            String qName = attributes.getQName(i);
            attributeContent.append(" the qName of index i=[").append(i).append("] is ").append(qName).append("\n");
            String localName = attributes.getLocalName(i);
            attributeContent.append(" the localName of index i=[").append(i).append("] is ").append(localName).append("\n");
            String value = attributes.getValue(i);
            attributeContent.append(" the value of index i=[").append(i).append("] is ").append(value).append("\n");
            String type = attributes.getType(i);
            attributeContent.append(" the type of index i=[").append(i).append("] is ").append(type).append("\n");
        }
        return attributeContent.toString();
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        System.out.println("====endElement(uri==>" + uri + ",localName==>" + localName + ",qName==>" + qName + ")");


    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        String value = new String(ch, start, length).trim();
        System.out.println("characters--------" + value);
    }
}
